<?php
// +----------------------------------------------------------------------
// | Copyright © Sogu Technologies Co. Ltd 2018-2050 All rights reserved.
// +----------------------------------------------------------------------
// | File name: Repay.php
// +----------------------------------------------------------------------
// | Author: gxs
// +----------------------------------------------------------------------
// | Description: 还款逻辑trait
// +----------------------------------------------------------------------
// | Others: 其他内容的说明
// +----------------------------------------------------------------------
// | History: 修改历史记录列表，每条修改记录应包含修改日期、修改者及修改内容简述
// +----------------------------------------------------------------------
// | 1.Date: 2019/1/10 Author: gxs Modification: 创建
// +----------------------------------------------------------------------

namespace App\Models\Traits;

use App\Events\CollectionReceiptEvent;
use App\Facades\MoneyPlatformRequestFacade;
use App\Library\ArrayTools\ArrayTools;
use App\Library\Traits\RepaySmsRemind as RepaySmsRemindTrait;
use App\Models\LoanApply;
use App\Models\RepayRecord as RepayRecordModel;
use App\Models\RepayRecordCommon;
use App\Models\RepayRecordMoney;
use App\Models\RepayRecordMonth;
use App\Models\RepaySummary as RepaySummaryModel;
use App\Models\UserBankCard;
use App\Models\UserGlobal;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use MathPHP\Finance;

trait Repay
{
    /**
     * Description: 从放款LoanApply对象中解析summary创建数据
     * Author: Gxs
     * @param LoanApply $apply
     * @return array
     */
    public static function parseDataFromLoanApplyModel(LoanApply $apply)
    {
        $result = [
            'uid' => $apply->user_id,
            'loan_request_id' => $apply->loan_request_id,
            'loan_id' => $apply->loan_id,
            'amount' => $apply->amount,
            'period_count' => $apply->period,
            'rate' => [
                'lending_rate' => $apply->lending_rate,
                'insurance_rate' => $apply->insurance_rate,
                'month_insurance_rate' => $apply->month_insurance_rate,
                'manage_rate' => $apply->manage_rate,
                'repayment_rate' => $apply->repayment_rate,
                'fines_rate' => $apply->fines_rate,
            ],
        ];
        return $result;
    }

    /**
     * Description: 从还款计划表获取还款分期数据
     * Author: Gxs
     * @param $loan_id
     * @param int $period
     * @return array|bool
     */
    public static function mapMoneyDataFromThirdApi($loan_id, $period = 0)
    {
        $repay_plan_list = MoneyPlatformRequestFacade::getRepayPlan(['loanId' => $loan_id, 'period' => $period,]);
        Log::debug('money_plat_form',['result'=>$repay_plan_list, 'loanId' => $loan_id]);
        if (!$repay_plan_list)
            return false;
        return $repay_plan_list['data'];
    }

    /**
     * Description: 从还款计划数据中处理各记录表所需数据
     * Author: Gxs
     * @param $data
     * @param LoanApply $apply
     * @param RepaySummaryModel $summary
     * @return array
     */
    public static function parseRecordDataFromRepayPlan($data, LoanApply $apply, RepaySummaryModel $summary)
    {
        if (count($data) == count($data, 1)) {
            $one = true;
            $record = self::_oneRecord($data, $apply, $summary); //一期数据解析 记录
        } else {
            $one = false;
            $record = self::_moreRecord($data, $apply, $summary); //多期数据解析
        }
        $result = ['one' => $one, 'data' => $record,];
        return $result;
    }

    /**
     * Description: 月保接口数据
     * Author: Gxs
     * @param $data
     * @param RepaySummaryModel $summary
     * @return array
     */
    public static function parseMonthDataFromRecord($data, RepaySummaryModel $summary)
    {
        if (count($data) == count($data, 1)) {
            $one = true;
            $month = self::_oneMonth($data, $summary);
        } else {
            $one = false;
            $month = self::_moreMonth($data, $summary);
        }
        $result = ['one' => $one, 'data' => $month,];
        return $result;
    }

    /**
     * Description: 公共接口数据
     * Author: Gxs
     * @param array $data 记录表数据
     * @param array $money_data 资方数据
     * @param RepaySummaryModel $summary
     * @return array
     */
    public static function parseCommonDataFromRecord($data, $money_data, RepaySummaryModel $summary)
    {
        if (count($data) == count($data, 1)) {
            $one = true;
            $month = self::_oneCommon($data, $money_data, $summary);
        } else {
            $one = false;
            $month = self::_moreCommon($data, $money_data, $summary);
        }
        $result = ['one' => $one, 'data' => $month,];
        return $result;
    }

    /**
     * Description: 资方接口数据
     * Author: Gxs
     * @param $data
     * @param $record
     * @return array
     */
    public static function parseMoneyDataFromRepayPlan($data, $record)
    {
        if (count($data) == count($data, 1)) {
            $one = true;
            $money = self::_oneMoney($data, $record);
        } else {
            $one = false;
            $money = self::_moreMoney($data, $record);
        }
        $result = ['one' => $one, 'data' => $money,];
        return $result;
    }

    /**
     * Description: 平台利息试算
     * Description Change: 2019-02-21 变更为合计(平台+资方)利息试算
     * Author: Gxs
     * @param int $amount 总本金 单位元
     * @param array $rate 平台利率配置
     * @param int $period 当前期数
     * @param int $period_count 总期数
     * @return array|bool
     */
    public static function trial($amount, $rate, $period = 1, $period_count = 12)
    {
        if (
            !isset($rate['month_insurance_rate']) || !isset($rate['lending_rate']) ||
            !isset($rate['manage_rate']) || !isset($rate['repayment_rate'])
        )
            return false;
        $month_money = round(bcmul($amount, $rate['month_insurance_rate']));
        $lending_money = abs(Finance::ipmt(bcdiv($rate['lending_rate'], 12, 8), $period, $period_count, $amount));
        $manage_money = bcmul($amount, $rate['manage_rate']);
        return [
            'month_money' => $month_money, //合计月保费(暂时平台扣费为0)
            'lending_money' => $lending_money, //合计利息费
            'manage_money' => $manage_money, //合计管理费
        ];
    }

    /**
     * Description: 提前还清手续费 还款计划表总利息-还款计划表前几期利息
     * Author: Gxs
     * @param int $period
     * @param $summary_id
     * @return int|string
     */
    public static function repaymentMoney($period = 1, $summary_id)
    {
        $summary_model = RepaySummaryModel::find($summary_id);
        $common_collection = $summary_model->common->where('status', '<>', RepayRecordCommon::STATUS_FOUR);
        $money_collection = $summary_model->money->where('status', '<>', RepayRecordCommon::STATUS_FOUR)->where('period','<>',0);
        //lending_money
        $common_lending = $common_collection->sum('lending_money');
        $money_lending = $money_collection->sum('lending_money');
        $lending_money = bcadd($common_lending, $money_lending, 2);
        //manage_money
        $common_manage = $common_collection->sum('manage_money');
        $money_manage = $money_collection->sum('manage_money');
        $manage_money = bcadd($common_manage, $money_manage, 2);
        $repayment_money = bcadd($lending_money, $manage_money, 2);
        return $repayment_money;
    }

    /**
     * Description: 单期记录生成
     * Author: Gxs
     * @param $data
     * @param LoanApply $apply
     * @param RepaySummaryModel $summary
     * @return array
     */
    private static function _oneRecord($data, LoanApply $apply, RepaySummaryModel $summary)
    {
        //记录表
        $record = [
            'uid' => $summary->uid,
            'summary_id' => $summary->id,
            'bank_cards_id' => $apply->bank_card_id,
            'period' => $data['currentPeriod'],
            'amount' => $data['principalAmount'],
            'normal_date' => $data['repayDate']
        ];
        if (!empty($data['actualRepayDate']))
            $record['repay_date'] = $data['actualRepayDate'];
        return $record;
    }

    /**
     * Description: 多期记录生成
     * Author: Gxs
     * @param $data
     * @param LoanApply $apply
     * @param RepaySummaryModel $summary
     * @return array
     */
    private static function _moreRecord($data, LoanApply $apply, RepaySummaryModel $summary)
    {
        $record = [];
        if (!empty($data)) {
            foreach ($data as $key => $value) {
                $temp_record = [
                    'uid' => $summary->uid,
                    'summary_id' => $summary->id,
                    'bank_cards_id' => $apply->bank_card_id,
                    'period' => $value['currentPeriod'],
                    'amount' => $value['principalAmount'],
                    'normal_date' => $value['repayDate']
                ];
                if (!empty($value['actualRepayDate']))
                    $temp_record['repay_date'] = $value['actualRepayDate'];
                $record[] = $temp_record;
            }
        }
        return $record;
    }

    /**
     * Description: 资金单条
     * Author: Gxs
     * @param $data
     * @param $record
     * @return array
     */
    private static function _oneMoney($data, $record)
    {
        //资方接口表
        $record = [
            'uid' => $record['uid'],
            'summary_id' => $record['summary_id'],
            'record_id' => $record['id'],
            'bank_cards_id' => $record['bank_cards_id'],
            'period' => $data['currentPeriod'],
            'lending_money' => $data['interestAmount'],
            'fines_money' => $data['penaltyAmount'],
            'repayment_money' => $data['serviceAmount'],
        ];
        return $record;
    }

    /**
     * Description: 资金多条
     * Author: Gxs
     * @param $data
     * @param $record
     * @return array
     */
    private static function _moreMoney($data, $record)
    {
        $result = [];
        $data = ArrayTools::valueToKey($data, 'currentPeriod');
        //资方接口表
        foreach ($record as $key => $value) {
            $temp_data = $data[$value['period']];
            $temp_record = [
                'uid' => $value['uid'],
                'summary_id' => $value['summary_id'],
                'record_id' => $value['id'],
                'bank_cards_id' => $value['bank_cards_id'],
                'period' => $temp_data['currentPeriod'],
                'lending_money' => $temp_data['interestAmount'],
                'fines_money' => $temp_data['penaltyAmount'],
                'repayment_money' => $temp_data['serviceAmount'],
            ];
            $result[] = $temp_record;
        }
        return $result;
    }

    /**
     * Description: 月报单条
     * Author: Gxs
     * @param $data
     * @param RepaySummaryModel $summary
     * @return array
     */
    private static function _oneMonth($data, RepaySummaryModel $summary)
    {
        $trial_result = self::trial($summary['amount'], $summary['rate']);
        //月报接口表
        $record = [
            'uid' => $data['uid'],
            'summary_id' => $data['summary_id'],
            'record_id' => $data['id'],
            'bank_cards_id' => $data['bank_cards_id'],
            'period' => $data['period'],
            'amount' => $trial_result['month_money'],
        ];
        return $record;
    }

    /**
     * Description: 月报多条
     * Author: Gxs
     * @param $data
     * @param RepaySummaryModel $summary
     * @return array
     */
    private static function _moreMonth($data, RepaySummaryModel $summary)
    {
        $result = [];
        if (!empty($data)) {
            $trial_result = self::trial($summary['amount'], $summary['rate']);
            foreach ($data as $key => $value) {
                $temp = [
                    'uid' => $value['uid'],
                    'summary_id' => $value['summary_id'],
                    'record_id' => $value['id'],
                    'bank_cards_id' => $value['bank_cards_id'],
                    'period' => $value['period'],
                    'amount' => $trial_result['month_money'], //月保费
                ];
                $result[] = $temp;
            }
        }
        return $result;
    }

    /**
     * Description: 公共单条
     * Author: Gxs
     * @param array $data 记录表数据
     * @param array $money_data 资方数据
     * @param RepaySummaryModel $summary
     * @return array
     */
    private static function _oneCommon($data, $money_data, RepaySummaryModel $summary)
    {
        $trial_result = self::trial($summary['amount'], $summary['rate'], $data['period'], $summary['period_count']);
        $loan_id = $summary['loan_id'];
        //公共接口表
        $record = [
            'uid' => $data['uid'],
            'summary_id' => $data['summary_id'],
            'record_id' => $data['id'],
            'bank_cards_id' => $data['bank_cards_id'],
            'period' => $data['period'],
            'lending_money' => 0, //利息费 公共平台暂定为0
            'manage_money' => $trial_result['manage_money'], //贷后管理费
            //提前还清手续费 1期 合计 - 资方
            'repayment_money' => 0,
        ];
        return $record;
    }

    /**
     * Description: 公共多条
     * Author: Gxs
     * @param array $data 记录表数据
     * @param array $money_data 资方数据
     * @param RepaySummaryModel $summary repay_summaries 表模型
     * @return array
     */
    private static function _moreCommon($data, $money_data, RepaySummaryModel $summary)
    {
        $result = [];
        $money_data = ArrayTools::valueToKey($money_data, 'period');
        if (!empty($data)) {
            //总本金
            $amount = $summary['amount'];
            $loan_id = $summary['loan_id'];
            $balance = $amount;
            foreach ($data as $key => $value) {
                $trial_result = self::trial($amount, $summary['rate'], $value['period'], $summary['period_count']);
                $temp = [
                    'uid' => $value['uid'],
                    'summary_id' => $value['summary_id'],
                    'record_id' => $value['id'],
                    'bank_cards_id' => $value['bank_cards_id'],
                    'period' => $value['period'],
                    'lending_money' => 0, //利息费 公共平台暂定为0
                    'manage_money' => $trial_result['manage_money'], //贷后管理费 = 合计 - 资方(资方不存在管理费用，视为0)
                    //提前还清手续费 多期 合计 - 资方
                    'repayment_money' => 0,
                ];
                //剩余本金
                $balance = bcsub($balance, $value['amount'], 2);
                $result[] = $temp;
            }
        }
        return $result;
    }

    /**
     * Description: 获取用户最新借款记录
     * Author: Gxs
     * @param RepaySummaryModel $summary_model
     * @return array 借款记录 && 还款计划表
     */
    public static function getFrontRepayList($summary_model)
    {
        $result = [];
        $plan = [];
        $list = $summary_model->recordMany->where('period','<>',0);//2019-04-12 修改 过滤期数为0 数据
        $period_count = $summary_model->period_count; //本地还款总期数
        $loan_time = Carbon::createFromTimeString($summary_model->relationLoanApply->loan_time)->format('Y·m·d'); //真实放款日期
        $trans_money_list = $summary_model->relationLoanApply->trans_money_list; //放款明细的
//        //获取投保单号-_-
        $pay_order_number = self::getPayOrderNo($trans_money_list);
        $bank_cards_info = UserBankCard::getCardInfoByBankCardId($summary_model->relationProcessingRecord->bank_cards_id); //银行卡信息
        foreach ($list as $key=>$value) {
            //还款计划表
            $temp_plan = [
                'period_count' => $period_count, //总期数
                'period' => $value->period, //借款期数/当前期数
                'amount' => $value->amount, //借款本金/应还本金
            ];
            $temp = [
                'period_count' => $period_count, //总期数
                'loan_time' => $loan_time, //借款日期
                'pay_order_number' => $pay_order_number, //投保单号
                'period' => $value->period, //借款期数
                'amount' => $value->amount, //借款本金
                'normal_date' => is_null($value->normal_date) ? null : Carbon::createFromFormat('Y-m-d', $value->normal_date)->format('Y·m·d'), //正常还款日期
                'repay_date' => is_null($value->repay_date) ? null : Carbon::createFromFormat('Y-m-d', $value->repay_date)->format('Y·m·d'), //实际还款日期
            ];
            $lending_amount = bcadd($value->common->lending_money, $value->money->lending_money, 2); //总利息
            $manage_amount = bcadd($value->common->manage_money, $value->money->manage_money, 2); //总管理费
            $common_lending_manage = bcadd($value->common->lending_money, $value->common->manage_money, 2); //平台利息 + 管理费
            $money_lending_manage = bcadd($value->money->lending_money, $value->money->manage_money, 2); //资方利息 + 管理费
            $repay_amount = bcadd(bcadd(bcadd($common_lending_manage, $money_lending_manage, 2), $value->month->amount, 2), $value->amount, 2); //本期应还 = 实还金额
            $temp_plan['lending_amount'] = $lending_amount; //利息
            $temp_plan['other_amount'] = bcadd($manage_amount, $value->month->amount, 2); //总管理费/还款计划表中的其他

            $get_result_result = self::getOtherMoneyAndType($summary_model, $value); //状态判断 && (罚息计算 || 还款手续费计算)
            $type = $get_result_result['type'];
            $fines_amount = $get_result_result['fines_amount'];
            $pay_off_amount = $get_result_result['pay_off_amount'];
            $overdue_day = $get_result_result['overdue_day'];
            $repay_amount = bcadd(bcadd($fines_amount, $pay_off_amount, 2), $repay_amount, 2);
            $temp['type'] = $type;
            $temp['repay_amount'] = $repay_amount;
            $temp['fines_amount'] = $fines_amount;
            $temp['overdue_day'] = $overdue_day;
//            print_r(UserBankCard::getCardInfoByBankCardId($value->bank_cards_id));exit;
            $temp['bank_cards_info'] = $bank_cards_info; //银行卡信息
            $temp_plan['type'] = $type;
            $result[] = $temp;
            $plan[] = $temp_plan;
        }
        return [
            'record_list' => $result,
            'repay_plan' => $plan,
        ];
    }

    /**
     * Description: 获取投保单号-_-
     * Author: Gxs
     * @param $trans_money_list
     * @return int
     */
    public static function getPayOrderNo($trans_money_list)
    {
        //获取投保单号-_-
        $pay_order_number = 0;
        if (!empty($trans_money_list)) {
            foreach ($trans_money_list as $item) {
                if (!empty($item['policyNo']) && $item['transType'] === '01')
                    $pay_order_number = $item['policyNo'];
            }
        }
        return $pay_order_number;
    }

    /**
     * Description: 根据单期还款数据计算状态 与 平台附加收费(罚息 || 提前还清手续费)
     * Author: Gxs
     * @param RepaySummaryModel $summary_model
     * @param RepayRecordModel $value
     * @return array
     */
    public static function getOtherMoneyAndType($summary_model, RepayRecordModel $value)
    {
        //状态
        $overdue_day = 0; //逾期天数
        $fines_amount = '0.00'; //罚息
        $pay_off_amount = '0.00'; //提前还清手续费
        if (RepayRecordModel::STATUS_FOUR == $value->status) {
            //还款成功 已还 逾期数据 结清
            $type = RepayRecordModel::RETURN_TYPE_THREE;
            if (RepayRecordModel::PAY_OFF_TWO == $value->pay_off) {
                $type = RepayRecordModel::RETURN_TYPE_FIVE;
                $pay_off_amount = bcadd($value->common->repayment_money, $value->money->repayment_money, 2); //提前结清手续费
            }
            $fines_amount = bcadd($value->common->fines_money, $value->money->fines_money, 2); //罚息
            $normal_date = Carbon::createFromFormat('Y-m-d', $value->normal_date);
            $repay_date = Carbon::createFromFormat('Y-m-d', $value->repay_date);
            $diff_days = $normal_date->diffInDays($repay_date, false); //逾期天数
            if ($diff_days > 0)
                $overdue_day = $diff_days;
        } else {
            //待还
            $type = RepayRecordModel::RETURN_TYPE_ONE;
            $current_date = Carbon::now();
            $normal_date = Carbon::createFromFormat('Y-m-d', $value->normal_date);
            $diff_days = $normal_date->diffInDays($current_date, false); //逾期天数
            if ($diff_days > 0) {
                //逾期
                $type = RepayRecordModel::RETURN_TYPE_TWO;
                $fines_amount = bcadd($value->common->fines_money, $value->money->fines_money, 2); //罚息
//                $fines_money = RepaySummaryModel::getFines($value->normal_date,$summary_model['rate']['fines_rate'],$summary_model['amount'],$value->common->id); //平台罚息
//                $common_fines_amount = $fines_money['common_fines_money'];
//                $money_fines_amount = $fines_money['money_fines_money'];
//                $fines_amount = bcadd($common_fines_amount, $money_fines_amount, 2); //罚息
                $overdue_day = $diff_days;
            }
        }
        return [
            'type' => $type,
            'overdue_day' => $overdue_day,
            'fines_amount' => $fines_amount,
            'pay_off_amount' => $pay_off_amount,
        ];
    }

    /**
     * Description: 设置常规流程(资方-月保-公共,最后顺序队列调用逻辑)失败(现在为common失败后调用)
     * Author: Gxs
     * @param RepayRecordCommon $model
     */
    public static function setNormalOrderFailure($model)
    {
        if (0 == $model->period) {
            //全部还清失败发送短信
            RepaySmsRemindTrait::sendSettlementFailureSms($model);
            //失败更新减免金额为0
            RepayRecordCommon::where('summary_id',$model->summary_id)
                ->where('status','!=',RepayRecordCommon::STATUS_FOUR)
                ->update(['relief_amount'=>0]);
        } else {
            //单期失败发送短信
            if (RepayRecordModel::REPAY_TYPE_AUTO == $model->repay_type) {
//                RepaySmsRemindTrait::sendAotuFailureSms($model); //自动
            } else {
                RepaySmsRemindTrait::sendHandleFailureSms($model); //手动
            }
            //失败更新减免金额为0
            $model->update(['relief_amount'=>0]);
        }
    }

    /**
     * Description: 设置常规流程(资方-月保-公共,最后顺序队列全部还清调用逻辑)全部还清(现在为common成功后调用)
     * Author: Gxs
     * @param RepayRecordCommon $model
     */
    public static function setNormalAllPeriodSuccess(RepayRecordCommon $model)
    {
        $summary_model = RepaySummaryModel::where('id', $model->summary_id)->first();

        event(new CollectionReceiptEvent($model->record_id));

        RepaySummaryModel::where('id', $model->summary_id)->update([
            'period'=> $summary_model->period_count,
            'status' => RepaySummaryModel::STATUS_TWO,
        ]); //summary 摘要表 最终状态变更

        $where = [
            ['summary_id', '=', $model->summary_id],
            ['status', '<>', RepayRecordModel::STATUS_FOUR],
        ];

        //记录总表
        RepayRecordModel::where($where)->update([
            'status' => RepayRecordModel::STATUS_FOUR,
            'failure_message' => '',
            'pay_off' => RepayRecordModel::PAY_OFF_TWO,
            'repay_date' => Carbon::now(),
        ]);
        UserGlobal::where('uid', $model->uid)->update(['global_status' => UserGlobal::STATUS_REPAY_OVER]); //全局状态
        RepaySmsRemindTrait::sendSettlementSuccessSms($summary_model, $model); //发送全部结清成功短信 todo 提到异步事件
    }

    /**
     * Description: 设置常规流程(资方-月保-公共,最后顺序队列单期还款调用逻辑)单期成功(现在为common成功后调用)
     * Author: Gxs
     * @param RepayRecordCommon $model
     */
    public static function setNormalCurrentPeriodSuccess(RepayRecordCommon $model)
    {
        $summary_model = RepaySummaryModel::where('id', $model->summary_id)->first();
        $period_count = $summary_model->period_count;

        //催收成功回执通知事件
        event(new CollectionReceiptEvent($model->record_id));

        if ($period_count == $model->period) {
            //最后一期还清
            RepaySummaryModel::where('id', $model->summary_id)->update([
                'period' => $model->period,
                'status' => RepaySummaryModel::STATUS_TWO,
            ]); //summary 摘要表 最终状态变更
            UserGlobal::where('uid', $model->uid)->update(['global_status' => UserGlobal::STATUS_REPAY_OVER]); //全局状态
        } else {
            RepaySummaryModel::where('id', $model->summary_id)->update(['period'=>(int)($model->period + 1),]); //summary表
            UserGlobal::where('uid', $model->uid)->update(['global_status' => UserGlobal::STATUS_REPAY_SUCCESS]); //全局状态
        }

        //记录总表
        RepayRecordModel::where('id', $model->record_id)->update([
            'status' => RepayRecordModel::STATUS_FOUR,
            'failure_message' => '',
            'repay_date' => Carbon::now(), //实际还款日期
        ]);

        //单期成功发送短信 todo 提到异步事件
        if (RepayRecordModel::REPAY_TYPE_AUTO == $model->repay_type) {
            RepaySmsRemindTrait::sendAotuSuccessSms($model->money); //自动
        } else {
            RepaySmsRemindTrait::sendHandleSuccessSms($model->money); //手动
        }
    }

    /**
     * Description: 设置当期所有数据为成功
     * Author: Gxs
     * @param $model
     * @param int $repay_type
     * @param bool $sms
     * @return bool
     */
    public static function setCurrentPeriodSuccess($model, $repay_type = RepayRecordModel::REPAY_TYPE_MANUAL, $sms = true)
    {
        try {
            DB::beginTransaction();
            $period_count = $model->relationSummary->period_count;
            //最后顺序队列单期还款调用逻辑
            if ($period_count == $model->period) {
                //最后一期还清
                RepaySummaryModel::where('id', $model->summary_id)->update([
                    'period' => $model->period,
                    'status' => RepaySummaryModel::STATUS_TWO,
                ]); //summary 摘要表 最终状态变更
                UserGlobal::where('uid', $model->uid)->update(['global_status' => UserGlobal::STATUS_REPAY_OVER]); //全局状态
            } else {
                RepaySummaryModel::where('id', $model->summary_id)->update(['period'=>(int)($model->period + 1),]); //summary表
                UserGlobal::where('uid', $model->uid)->update(['global_status' => UserGlobal::STATUS_REPAY_SUCCESS]); //全局状态
            }

            //记录总表
            RepayRecordModel::where('id', $model->id)->update([
                'status' => RepayRecordModel::STATUS_FOUR,
                'pay_off' => RepayRecordModel::PAY_OFF_ONE,
                'repay_date' => Carbon::now(), //实际还款日期
                'repay_type' => $repay_type,
            ]);

            //资方表
            $repay_plan_data = RepaySummaryModel::mapMoneyDataFromThirdApi($model->relationSummary->loan_id,$model->period);
            Log::debug('set_current_period_success_repay_plan_data', ['data' => $repay_plan_data, 'summary_id' => $model->summary_id]);
            if (!$repay_plan_data) {
                $repay_plan_data = [];
            }
            if (!isset($repay_plan_data['actualRepayDate']) || false == strtotime($repay_plan_data['actualRepayDate'])) {
                $repay_date = Carbon::now()->toDateString();
            } else {
                $repay_date = Carbon::createFromTimeString($repay_plan_data['actualRepayDate'])->toDateString();
            }
            RepayRecordMoney::where('record_id', $model->id)
                ->where('period', $model->period)
                ->update([
                    'status' => RepayRecordModel::STATUS_FOUR,
                    'apply_time' => Carbon::now(), //默认为当前时间
                    'status_time' => Carbon::now(), //实际还款日期
                    'manage_money' => 0, //提前结清的贷后管理费0
                    'repay_date' => $repay_date, //实际还款日期
                    'repay_type' => $repay_type,
                    'type' => empty($repay_plan_data) ? 0 : RepayRecordMoney::$third_map_type[$repay_plan_data['status']]
            ]);

            //月保费表
            RepayRecordMonth::where('record_id', $model->id)
                ->where('period', $model->period)
                ->update([
                    'status' => RepayRecordModel::STATUS_FOUR,
                    'status_time' => Carbon::now(), //实际还款日期
                    'apply_time' => Carbon::now(), //实际还款日期
                    'repay_type' => $repay_type,
            ]);

            //公共平台表
            RepayRecordCommon::where('record_id', $model->id)
                ->where('period', $model->period)
                ->update([
                    'status' => RepayRecordModel::STATUS_FOUR,
                    'status_time' => Carbon::now(), //实际还款日期
                    'apply_time' => Carbon::now(), //实际还款日期
                    'repay_type' => $repay_type,
            ]);

            if ($sms) {
                //单期所有数据成功发送短信
                if (RepayRecordModel::REPAY_TYPE_AUTO == $model->repay_type) {
                    RepaySmsRemindTrait::sendAotuSuccessSms($model->money); //自动
                } else {
                    RepaySmsRemindTrait::sendHandleSuccessSms($model->money); //手动
                }
            }
            DB::commit();
            return true;
        } catch (\Exception $e) {
            Log::debug('set_current_period_success', ['message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            DB::rollBack();
            return false;
        }
    }

    /**
     * Description: 设置订单(所有未成功)为成功
     * Author: Gxs
     * @param $model
     * @param int $repay_type
     * @param bool $sms
     * @return bool
     */
    public static function setAllPeriodSuccess($model, $repay_type = RepayRecordModel::REPAY_TYPE_MANUAL, $sms = true)
    {
        try {
            DB::beginTransaction();
            $summary_model = RepaySummaryModel::where('id', $model->summary_id)->first();
            RepaySummaryModel::where('id', $model->summary_id)->update([
                'period' => $summary_model->period_count,
                'status' => RepaySummaryModel::STATUS_TWO,
            ]); //summary 摘要表 最终状态变更

            $repay_plan_data = RepaySummaryModel::mapMoneyDataFromThirdApi($summary_model->loan_id); //全部还款计划表
            Log::debug('set_all_period_success_repay_plan_data', ['data' => $repay_plan_data, 'summary_id' => $model->summary_id]);
            if ($repay_plan_data) {
                $end_data = end($repay_plan_data);
            } else {
                $end_data = [];
            }
            $where = [
                ['summary_id', '=', $model->summary_id],
                ['status', '<>', RepayRecordModel::STATUS_FOUR],
            ];

            //记录总表
            RepayRecordModel::where($where)->update([
                'status' => RepayRecordModel::STATUS_FOUR,
                'pay_off' => RepayRecordModel::PAY_OFF_TWO,
                'repay_date' => Carbon::now(), //实际还款日期
                'repay_type' => $repay_type,
            ]);

            //资方表
            if (!isset($end_data['actualRepayDate']) || false == strtotime($end_data['actualRepayDate'])) {
                $repay_date = Carbon::now()->toDateString();
            } else {
                $repay_date =  Carbon::createFromTimeString($end_data['actualRepayDate'])->toDateString();
            }
            RepayRecordMoney::where($where)->update([
                'status' => RepayRecordModel::STATUS_FOUR,
                'apply_time' => Carbon::now(), //默认为当前时间
                'status_time' => Carbon::now(), //实际还款日期
                'repay_date' => $repay_date, //实际还款日期
                'manage_money' => 0, //提前结清的贷后管理费0
                'repay_type' => $repay_type,
                'type' => empty($end_data) ? 0 : RepayRecordMoney::$third_map_type[$end_data['status']],
            ]);

            //月保费表
            RepayRecordMonth::where($where)->update([
                'status' => RepayRecordModel::STATUS_FOUR,
                'apply_time' => Carbon::now(), //实际还款日期
                'status_time' => Carbon::now(), //实际还款日期
                'repay_type' => $repay_type,
            ]);

            //公共平台表
            RepayRecordCommon::where($where)->update([
                'status' => RepayRecordModel::STATUS_FOUR,
                'apply_time' => Carbon::now(), //实际还款日期
                'status_time' => Carbon::now(), //实际还款日期
                'repay_type' => $repay_type,
            ]);

            UserGlobal::where('uid', $model->uid)->update(['global_status' => UserGlobal::STATUS_REPAY_OVER]); //全局状态
            if ($sms) {
                RepaySmsRemindTrait::sendSettlementSuccessSms($summary_model, $model); //发送全部结清成功短信
            }
            DB::commit();
            return true;
        } catch (\Exception $e) {
            print_r($e->getMessage());
            Log::debug('set_all_period_success', ['message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            DB::rollBack();
            return false;
        }
    }
}